package com.atguigu.tingshu.user.service.impl;

import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Autowired
	private UserPaidAlbumMapper userPaidAlbumMapper;
	@Autowired
	private UserPaidTrackMapper userPaidTrackMapper;

	@Override
	// @GuiGuCache(prefix = "userInfo:")
	public UserInfoVo getUserInfoVo(Long userId) {
		//从通过用户ID从缓存中获取用户数据
		UserInfo userInfo = this.getById(userId);
		//创建vo对象
		UserInfoVo userInfoVo = new UserInfoVo();
		//属性拷贝
		BeanUtils.copyProperties(userInfo, userInfoVo);
		//返回数据
		return userInfoVo;
	}

	@Override
	public Map<Long, Integer> userIsPaidTrack(Long albumId, List<Long> trackIdList, Long userId) {
		//user_paid_album
		UserPaidAlbum userPaidAlbum = userPaidAlbumMapper.selectOne(new LambdaQueryWrapper<UserPaidAlbum>().eq(UserPaidAlbum::getAlbumId, albumId).eq(UserPaidAlbum::getUserId, userId));
		//判断用户是否购买了该专辑
		if (null != userPaidAlbum) {
			//	购买过这个专辑.
			Map<Long, Integer> map = trackIdList.stream().collect(Collectors.toMap(trackId -> trackId, trackId -> 1));
			//	返回数据
			return map;
		} else {
			//用户没有购买过专辑,判断用户是否购买过某集声音user_paid_track
			LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<>();
			wrapper.eq(UserPaidTrack::getUserId, userId).in(UserPaidTrack::getTrackId, trackIdList);
			List<Long> trackIdPaidList = userPaidTrackMapper.selectList(wrapper).stream().map(userPaidTrack -> userPaidTrack.getTrackId()).collect(Collectors.toList());
			//	创建一个map 集合
			Map<Long, Integer> map = new HashMap<>();
			//	循环遍历.
			trackIdList.stream().forEach(trackId -> {
				//	判断用户是否购买过声音Id
				if (trackIdPaidList.contains(trackId)) {
					//	购买过声音
					map.put(trackId, 1);
				} else {
					//	没有购买声音
					map.put(trackId, 0);
				}
			});
			return map;
		}
	}
}
